package com.twotiger.and.activity.current;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.account.recharge.RechargePage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.CurrentEnter;
import com.twotiger.and.bean.CurrentProject;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.URLUtil;
import com.twotiger.and.util.ViewUtils;

/**
 * 活期转入
 * @Description: TODO(这里描述这个类的作用) 
 * @Author douxy
 * @Date 2015年8月12日 下午2:50:58
 */
public class CurrentInputAmountPage extends BaseActivity implements OnClickListener {
    private static final int GETASSERTSUCCES = 0;
    private static final int GETASSERTFAIL = 1;
    private static final int CURRENT_PROJECTXINSUCCES = 2;
    private static final int CURRENT_PROJECTXINFAIL = 3;

    private TextView tv_available_money;
    private TextView tv_can_enter_money;
    private Button btn_enter, all_enter_btn;
    private EditText input_amount_edit;
    private HashMap<String, String> parm;
    private UserAsset userAsset;
    private CurrentProject mCurrentProject;
    private TextView tv_amount_msg;
    private SubTitle subTitle;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.input_current_amount_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {

            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        subTitle.setTitle("转入活期");
        subTitle.hideBtns();
        subTitle.title_left_bt.setImageDrawable(this.getResources()
            .getDrawable(R.drawable.leftback));
        subTitle.title_left_bt.setVisibility(View.VISIBLE);

        tv_available_money = (TextView) view.findViewById(R.id.tv_available_money);
        input_amount_edit = (EditText) view.findViewById(R.id.input_amount_edit);
        all_enter_btn = (Button) view.findViewById(R.id.all_enter_btn);
        tv_can_enter_money = (TextView) view.findViewById(R.id.tv_can_enter_money);
        btn_enter = (Button) view.findViewById(R.id.btn_enter);
        tv_amount_msg = (TextView) view.findViewById(R.id.tv_amount_msg);

    }

    @Override
    public void onClick(View view) {

        if (view == null) {
            return;
        }

        switch (view.getId()) {
        case R.id.sub_title_right_tv:
            Intent in = new Intent(mContext, WebViewPage.class);
            in.putExtra("title", "服务协议");
            Map<String, String> contractmap = new HashMap<String, String>();
            contractmap.put("pType", mCurrentProject.getpType());
            contractmap.put("token", getToken());
            in.putExtra(
                "url",
                Constants.HOST + Constants.CONTRACT + "contractDemoHtml?"
                        + URLUtil.createContractUrl(contractmap, "3.0"));
            startNewActivity(in, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.sub_title_left_bt:
            onBackPress();
            break;
        case R.id.all_enter_btn: //全投
            if (mCurrentProject.getInAmount() != 0.00 && userAsset != null) {
                if (mCurrentProject.getInAmount() >= userAsset.avaliable) {//项目可投大于用户资金
                    input_amount_edit.setText(ArithUtils.coverMoney(userAsset.avaliable + ""));
                    input_amount_edit.setSelection(ArithUtils.coverMoney(userAsset.avaliable + "")
                        .length());
                } else {
                    input_amount_edit.setText(ArithUtils.coverMoney(mCurrentProject.getInAmount()
                                                                    + ""));
                    input_amount_edit.setSelection(ArithUtils.coverMoney(
                        mCurrentProject.getInAmount() + "").length());
                }

            }
            break;
        case R.id.btn_enter:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            final String input_amount = input_amount_edit.getText().toString().trim();
            if (StringUtils.isEmpty(input_amount) || Double.parseDouble(input_amount) == 0) {
                showToast("请输入转入金额");
                return;
            }
            if (mCurrentProject == null) {
                return;
            }
            if (0 == mCurrentProject.getInAmount()) {
                showToast("您的活期资产已达" + ArithUtils.coverMoney(mCurrentProject.getMaxInAmount() + "")
                          + "上限");
                return;
            }
            if (mCurrentProject.getMinInAmount() != 0) {
                if (Double.parseDouble(input_amount) < mCurrentProject.getMinInAmount()) {
                    showToast("转入金额" + ArithUtils.coverMoney(mCurrentProject.getMinInAmount() + "")
                              + "元起");
                    return;
                }
            }
            if (Double.parseDouble(input_amount) > mCurrentProject.getInAmount()) {
                showToast("最高转入" + ArithUtils.coverMoneyComma(mCurrentProject.getInAmount() + "")
                          + "元");
                return;
            }
            if (userAsset == null) {
                return;
            }
            if (Double.parseDouble(input_amount) > userAsset.avaliable) {
                PromptManager.showConfirmAlertCommon(mContext, 0, "账户余额不足",
                    "账户可用余额不足~", "取消", "去充值", true, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {

                        }

                        @Override
                        public void onClickCancel() {
                            Intent intent = new Intent(CurrentInputAmountPage.this,
                                RechargePage.class);
                            intent.putExtra("SCENE", RechargePage.SCENE_CURRENT);
                            intent.putExtra("CURRENT_AMOUNT", input_amount);
                            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out,
                                false);
                        }
                    });
                return;
            }
            PromptManager.showCurrentAlertHasBtn(mContext, "转入确认", "您将转入老虎活期\n金额：" + input_amount
                                                                   + "元", "确认转入", true,
                new ReChargeClickListener() {

                    @Override
                    public void onClickConfirm() {
                        doCurrentEnter();
                    }

                    @Override
                    public void onClickCancel() {

                    }
                });

            break;
        }
    }

    protected void doCurrentEnter() {
        parm.clear();
        parm.put("token", getToken());
        parm.put("amount", ArithUtils.coverMoney(input_amount_edit.getText().toString().trim()));
        getDate(parm, Constants.PROJECTXIN, handler, CURRENT_PROJECTXINSUCCES,
            CURRENT_PROJECTXINFAIL, true, false, false);
    }

    @Override
    protected void setListener() {

        all_enter_btn.setOnClickListener(this);
        btn_enter.setOnClickListener(this);
        subTitle.title_right_tv.setOnClickListener(this);

        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETASSERTSUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        userAsset = JSONObject.parseObject(result.data, UserAsset.class);
                        tv_available_money.setText(ArithUtils.coverMoneyComma(userAsset.avaliable
                                                                              + "")
                                                   + "元");
                    } else {
                        showToast(userAsset.codeDesc);
                    }
                    break;
                case GETASSERTFAIL:

                    break;
                case CURRENT_PROJECTXINSUCCES:
                    Basebean result_p = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_p.isOk()) {
                        CurrentEnter mCurrentEnter = JSONObject.parseObject(result_p.data,
                            CurrentEnter.class);
                        Intent intent = new Intent(mContext, CurrentEnterSuccessPage.class);
                        intent.putExtra("CURRENTENTERSUC", mCurrentEnter);
                        startNewActivityforresult(intent, R.anim.push_left_in,
                            R.anim.push_left_out, CurrentHost.CURRENTREQUEST);
                    }else {
                        Intent intent = new Intent(mContext, CurrentEnterSuccessPage.class);
                        intent.putExtra("CURRENTENTERFAIL", result_p);
                        startNewActivityforresult(intent, R.anim.push_left_in,
                            R.anim.push_left_out, CurrentHost.CURRENTREQUEST);
                    }
                    break;
                case CURRENT_PROJECTXINFAIL:
                    showToast("网络异常");
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
        super.onActivityResult(requestcode, resultcode, intent);
        if (requestcode == CurrentHost.CURRENTREQUEST) {
            if (resultcode == CurrentHost.CURRENTRESULTCLOSE_SUC) {
                setResult(CurrentHost.CURRENTRESULTCLOSE_SUC);
                finish();
            } else if (resultcode == CurrentHost.CURRENTRESULTCLOSE_FAI) {
                setResult(CurrentHost.CURRENTRESULTCLOSE_FAI);
                finish();
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getuserassert();
    }

    @Override
    protected void processLogic() {
        parm = getParm();

        input_amount_edit.requestFocus();
        //弹出键盘
        this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        mCurrentProject = (CurrentProject) getIntent().getSerializableExtra("CURRENTPROJECT");

        getuserassert();

        initPage();
    }

    private void initPage() {
        if (mCurrentProject == null) {
            return;
        }
        tv_can_enter_money.setText(ArithUtils.coverMoneyComma(mCurrentProject.getInAmount() + ""));
        tv_amount_msg.setText(mCurrentProject.getAmountBoutiqueMsg());
        input_amount_edit.setHint("请输入金额("
                                  + ArithUtils.coverMoney(mCurrentProject.getMinInAmount() + "")
                                  + "元起)");
        //根据pType字段的返回是否为空，来判断协议是否显示
        if (StringUtils.isEmpty(mCurrentProject.getpType())) {
            subTitle.title_right_tv.setVisibility(View.GONE);
        } else {
            subTitle.title_right_tv.setVisibility(View.VISIBLE);
        }
        subTitle.title_right_tv.setText("协议");
    }

    private void getuserassert() {
        parm.clear();
        parm.put("token", getToken());
        getDate(parm, Constants.ASSETQUERY, handler, GETASSERTSUCCES, GETASSERTFAIL, false, true,
            false);
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.silent_anim, R.anim.slide_out_to_bottom);
    }

}
